<template>
  <div>
    <div>
      <Head
        :isSubordinate="isSubordinate"
        :buildId="buildId"
        @returnScene="returnSceneShow"
      />
      <div class="userInfo" v-if="userInfoShow">
        <InfoLayer
          :infoLayerData="userInfo"
          :householder="householder"
          @toCloseLayer="toCloseLayer"
          @toDetail="toDetail"
        />
      </div>
      <div class="infoEdit">
        <div class="infoEditbody">
          <slidemodel :placement="'top'" :showSlid="InfoEditShow">
            <InfoEdit :buildId="buildId" @toCloseInfoEdit="toCloseInfoEdit" />
          </slidemodel>
        </div>
      </div>
      <div class="indexposation">
        <div class="flex">
          <div v-if="!show" class="leftshow" @click="leftClick">
            <img src="../assets/images/iconOpen.png" />
          </div>
          <slidemodel :placement="'left'" :showSlid="show">
            <LeftEchart
              :buildId="buildId"
              :isSubordinate="isSubordinate"
              @toClose="toClose"
              @getWindows="getWindows"
              @closeWindows="closeWindows"
              @isbinding="isbinding"
            />
          </slidemodel>
          <slidemodel :placement="'left'" :showSlid="BindShow">
            <Binding
              :bindData="bindData"
              :windowsData="windowsData"
              :lightBindWindow="lightBindWindow"
              @lightwindow="clicklight2"
              @toBack="exitBind"
              @addBing="bindW"
              @delBing="delBing"
              @toSubmit="ensureBind"
              @toCloseBind="toCloseBind"
            />
          </slidemodel>
          <div class="right">
            <slidemodel :placement="'right'" :showSlid="showSlid">
              <Detail :detail="detail" @toBack="toBack" />
            </slidemodel>
          </div>
        </div>
      </div>
      <!-- <div class="homeBg" v-show="!isSubordinate">
        <div class="homeBtn" @click="returnSceneShow">
          <div class="homrIcon"><i class="iconfont icon-shouye"></i></div>
          <div class="homeText">首页</div>
        </div>
      </div> -->
    </div>
    <div class="layer-cesium">
      <div
        id="cesiumContainer"
        v-loading="loading"
        element-loading-text="场景加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.9)"
      ></div>
    </div>
    <div class="homebuild">
      <div class="infoEditbody">
        <div class="homemodal" v-if="isShowJoined">
          <div class="homemodalcontent">
            <div class="homemodalhead">
              <div class="homemodalheadDiv">
                <div class="homemodalheadText">
                  <img src="../assets/images/point.png" alt="" />
                  请先选择楼栋
                </div>
                <div class="dataEdit">
                  <el-button
                    icon="el-icon-close"
                    circle
                    @click="closehomemodal"
                  ></el-button>
                </div>
              </div>
              <img class="splitLine" src="../assets/images/Divider5.png" />
            </div>
            <div class="homemodalbody">
              <div v-for="(item, index) in options" :key="index">
                <div class="homemodallable" @click="getJoinedInfo(item.label)">
                  {{ item.label }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="homebuild" v-show="modelDataShow">
      <div class="infoEditbody">
        <div class="homemodal">
          <div class="homemodalcontent">
            <div class="homemodalhead">
              <div class="homemodalheadText">
                <img src="../assets/images/point.png" alt="" />
                {{ modelTitle }}
              </div>
              <img class="splitLine" src="../assets/images/Divider5.png" />
            </div>
            <div class="bindmodalbody">
              <div>
                是否解除
                <span class="bindred" v-if="modelData"
                  >{{ modelData.parentName }} {{ modelData.name }}</span
                >
                户籍数据
              </div>
              <div class="bindtext">
                解除绑定后，楼宇无法与当前户籍数据进行关联，请谨慎操作！
              </div>
              <div class="bindbtn">
                <div class="addBingbtn" @click="submitBtndel()">确定</div>
                <div class="delBingbtn" @click="modelClose()">取消</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <div class="bind" v-show="isInit != 0">
      <el-button @click="startBind(this.entities)">开启绑定</el-button>
      <el-button @click="bindW">添加绑定</el-button>
      <el-button @click="ensureBind">保存</el-button>
      <el-button @click="cancleBind(this.entities)">取消</el-button>
      <el-button @click="unBind">解绑</el-button>
      <el-button @click="exitBind">退出绑定</el-button>
    </div> -->
  </div>
</template>
<script>
window.rightDetail = function (id) {
  // console.log(window.mapVue.rightShow);
  window.mapVue.rightShow(id);
};
import * as Cesium from "cesium/Cesium";
import LeftEchart from "@/components/leftEchart.vue";
import Detail from "@/components/detail.vue";
import Basicdata from "../components/data";
import building from "../components/BuildingMap";
import axios from "axios";
import slidemodel from "@/components/slidemodel.vue";
import InfoEdit from "@/components/InfoEdit.vue";
import Head from "@/components/Head.vue";
import InfoLayer from "@/components/InfoLayer.vue";
import Binding from "@/components/Binding.vue";

export default {
  components: {
    LeftEchart,
    // RightEchart,
    Detail,
    slidemodel,
    InfoEdit,
    Head,
    InfoLayer,
    Binding,
  },
  name: "",
  data() {
    return {
      lightW: [],
      lightBindWindow: false,
      isBind: -1,
      // 多选绑定
      handlerBind: null,
      TypeColor: building.TypeColor,
      handlerBuild: null,
      buildiColor: Cesium.Color.fromCssColorString("#FFFFFF"),
      roadColor: Cesium.Color.fromCssColorString("#FFFFFF"),
      roadLabel: building.roadLabel,
      roadName: building.roadName,
      includeJoinedData: building.includeJoinedData,
      selectJoined: null,
      joinedInfo: null,
      isShowJoined: false,
      //连体建筑选择框
      options: [],
      value: "",
      isPickModel: false,
      joinedBuildData: building.joinedBuildData,
      joinedBuild: building.joinedBuild,
      buildingName: building.buildingName,
      buildingData: building.buildingData,
      handlerInfo: null,
      handler3D: null,
      dataDetail: Basicdata.dataDetail,
      loading: false,
      loadCount: null,
      show: false,
      labels: null,
      labelDatas: building.labelDatas,
      labelName: building.labelName,
      //模型初始位置
      modelPosition: null,
      models: [],
      listPosition: [],
      windowCount: 299,
      listInfo: [], //删除
      addDiv: null,
      addtitle: null,
      addcontent: null,
      addCloser: null,
      c: null,
      click_point: null,
      cartesian_2: null,
      isInit: null, //判断场景是否进入点击层级 0为初始化层级（点击建筑进入），1点击窗户查看信息，2为绑定窗户
      changedC: null,
      isVisible: true,
      viewer: null,
      entities: null,
      locatEntity: null,
      //根据点击建筑动态构建label对象
      labelA10: {
        lon: 103.262259,
        lat: 26.422797,
        height: 80,
        name: "A5-10",
      },
      buildId: "null",
      windowId: "",
      userInfo: [],
      isSubordinate: false,
      showSlid: false,
      userInfoShow: false,
      InfoEditShow: false,
      BindShow: false,
      householder: {
        name: "暂无住户信息",
        address: "暂无住户信息",
      },
      backImg: {
        image: "build_pop_s.png",
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 3000),
      },
      detail: {},
      bindData: {},
      windowsData: [],
      modelDataShow: false,
      modelTitle: "",
      modelData: null,
    };
  },
  mounted() {
    window.mapVue = this;
    this.initScene();
    this.addAllHouse();
    this.addGeoJson();
    this.labels = this.viewer.entities.add(new Cesium.Entity());
    this.putLabels(
      this.labelName,
      this.labels,
      this.viewer,
      this.labelDatas,
      this.buildiColor,
      this.backImg,
      Cesium.HeightReference.NONE
    );
    //css11
    this.putLabels(
      this.roadName,
      this.labels,
      this.viewer,
      this.roadLabel,
      this.roadColor,
      null,
      Cesium.HeightReference.CLAMP_TO_GROUND
    );
    // this.labels.show = true;
    this.add3dTiles(this.viewer);
  },
  watch: {
    isInit(newInit, oldInit) {
      console.log("isInit由" + oldInit + "变为" + newInit);
      this.isInit = newInit;
      if (this.isInit == 0) {
        this.isSubordinate = false;

        this.selectModel(this.viewer, this.entities);
      } else if (this.isInit == 1) {
        this.isSubordinate = true;
        this.clickEve(this.viewer, this.entities);
      } else if (this.isInit == 2) {
        this.lightW = [];
        let param = {
          buildName: this.bindData.name,
        };
        this.$axios.getBindWindow(param).then((res) => {
          if (res.code == 200) {
            this.lightwindow(this.entities, res.data, 2);
          }
        });
      }
    },
  },
  methods: {
    //打开绑定页面
    isbinding() {
      this.BindShow = true;
      this.$axios
        .getBuildTree({
          buildName: this.buildId,
        })
        .then((res) => {
          if (res.code == 200) {
            this.bindData = res.data;
            this.isInit = 2;
            // this.resetWindowColor(this.entities);
          }
        });

      let param = {
        buildName: this.buildId,
      };
      this.$axios.getBindWindow(param).then((res) => {
        if (res.code == 200) {
          this.lightwindow(this.entities, res.data, 2);
        }
      });
      // this.startBind(this.entities);
    },
    //重置特定窗子颜色
    resetSpecificW(lightW) {
      for (let i = 0; i < lightW.length; i++) {
        console.log(lightW[i]);
        for (let j = 0; j < this.entities._entities._array.length; j++) {
          if (this.entities._entities._array[j].model) {
            console.log("999999999999999999999");
            console.log(this.entities._entities._array[j].name);
            if (this.entities._entities._array[j].id == lightW[i]) {
              this.entities._entities._array[j].model.color = null;
              break;
            }
          }
        }
      }
    },
    //点击高亮已绑定
    clicklight2(val) {
      let newArr = []; //新值
      if (val.childList != null) {
        val.childList.forEach((item) => {
          newArr.push(item.name);
        });
        if (Array.from(this.lightW).length == 0) {
          for (let i = 0; i < newArr.length; i++) {
            this.lightW.push(newArr[i]);
          }
          this.lightWindowNoClear(this.entities, Array.from(this.lightW), 1);
          this.lightBindWindow = true;
        } else if (Array.from(this.lightW).length > 0) {
          if (Array.from(this.lightW)[0] == newArr[0]) {
            //两次点击一个
            if (this.lightBindWindow == false) {
              this.lightBindWindow = true;
              this.lightWindowNoClear(
                this.entities,
                Array.from(this.lightW),
                1
              );
            } else if (this.lightBindWindow == true) {
              this.lightBindWindow = false;
              this.lightWindowNoClear(
                this.entities,
                Array.from(this.lightW),
                2
              );
            }
          } else if (Array.from(this.lightW)[0] != newArr[0]) {
            this.lightBindWindow = true;
            // this.lightWindowNoClear(this.entities, Array.from(this.lightW), 2);
            // 判断上次点击的窗户是否已经删除
            let param = {
              buildName: this.bindData.name,
            };
            this.$axios.getBindWindow(param).then((res) => {
              if (res.code == 200) {
                this.lightwindow(this.entities, res.data, 2);
                this.lightWindowNoClear(this.entities, newArr, 1);
              }
            });

            this.lightW = [];
            for (let i = 0; i < newArr.length; i++) {
              this.lightW.push(newArr[i]);
            }
          }
        }
      } else {
        this.$message.warning("户籍数据无效，请重试");
      }
    },

    clicklight(val) {
      if (this.lightBindWindow == false) {
        this.lightBindWindow = true;
        let arr = [];
        this.lightW = [];
        if (val.childList != null) {
          val.childList.forEach((item) => {
            arr.push(item.name);
            this.lightW.push(item.name);
          });
          this.lightWindowNoClear(this.entities, arr, 1);
        } else {
          this.$message.warning("户籍数据无效，请重试");
        }
      } else if (this.lightBindWindow == true) {
        this.lightBindWindow = false;
        this.lightWindowNoClear(this.entities, Array.from(this.lightW), 2);
      }
    },
    //添加绑定
    addBing(val) {
      let arr = [];
      if (val.childList != null) {
        val.childList.forEach((item) => {
          arr.push(item.name);
        });
        this.lightwindow(this.entities, arr, 1);
      } else {
        this.$message.error("户籍数据无效，请重试");
      }
    },

    //解绑
    delBing(val) {
      this.modelTitle = "解除警告";
      this.modelData = val;
      this.modelDataShow = true;
      this.windowsData = [];
    },
    //确定解绑
    submitBtndel() {
      let param = {
        roomId: this.modelData.name,
      };
      this.$axios.unBindWindow(param).then((res) => {
        if (res.code == 200) {
          this.$message.success("户籍数据解绑成功!");
          this.modelDataShow = false;
          this.modelData = null;
          this.isbinding();
        } else {
          this.$message.error("户籍数据解绑失败，请重试");
        }
      });
    },
    modelClose() {
      this.modelDataShow = false;
    },
    //取消绑定
    toCloseBind() {
      this.windowsData = [];
      // this.resetWindowColor(this.entities);
      let param = {
        buildName: this.bindData.name,
      };
      this.$axios.getBindWindow(param).then((res) => {
        if (res.code == 200) {
          this.lightwindow(this.entities, res.data, 2);
        }
      });
      this.isBind = 2;
    },

    unBind() {
      //回传房间号
    },
    exitBind() {
      this.BindShow = false;
      this.resetWindowColor(this.entities);
      this.isInit = 1;
    },
    startBind(entyties) {
      this.isInit = 2;
      this.resetWindowColor(entyties);
    },
    // 取消绑定
    cancleBind(entyties) {
      this.resetWindowColor(entyties);
      this.isBind = 2;
    },
    //绑定
    bindW() {
      let th = this;
      th.isBind = 0;
      this.resetWindowColor(this.entities);
      let param = {
        buildName: this.bindData.name,
      };
      this.windowsData = [];
      this.$axios.getBindWindow(param).then((res) => {
        if (res.code == 200) {
          this.lightwindow(this.entities, res.data, 2);
        }
      });
      th.bindWindow(this.viewer, this.entities, function (bindWindows) {
        // console.log("选择的窗户");
        // console.log(bindWindows);
        let arr = [...bindWindows];
        arr = [...new Set(arr)];
        th.windowsData = arr;
        //todo
        //填充窗户列表
      });
    },
    //确定绑定
    ensureBind(val) {
      console.log("aaaaa", [...this.windowsData].length);
      // let param = {
      //   roomId: val.name,
      //   windowId: [...this.windowsData],
      // };
      // console.log("param", param);
      if ([...this.windowsData].length == 0) {
        this.$message.warning("未选择窗体，请选择窗体进行绑定");
        return;
      }
      axios
        .post("/zz/room/bindWindow", {
          roomId: val.name,
          windowId: [...this.windowsData],
        })
        .then((res) => {
          // console.log(res);
          if (res.data.code == 200) {
            this.$message.success("户籍数据绑定成功!");
            this.isbinding();
            this.windowsData = [];
          } else {
            this.$message.error("户籍数据绑定失败，请重试");
          }
        });
      // this.resetWindowColor(this.entities);
      this.isBind = 1;
    },
    bindWindow(viewer, entyties, bindWindows) {
      this.removeAllHandler();
      let windowsList = [];
      // let bindList=[];
      this.handlerBind = new Cesium.ScreenSpaceEventHandler(
        viewer.scene.canvas
      );
      let th = this;
      th.handlerBind.setInputAction(
        function (movement) {
          if (th.isInit == 2) {
            var pick = viewer.scene.pick(movement.position);
            if (
              pick &&
              pick.id &&
              pick.id._position &&
              pick.id._id.indexOf("_w_") != -1
            ) {
              const pickId = pick.id._id;
              if (th.isBind == 0) {
                windowsList.push(pickId);
                bindWindows(windowsList);
                th.lightwindow(entyties, windowsList, 0);
              } else if (th.isBind == 1) {
                //todo
                // 回传数据
                th.isBind = 0;
                windowsList = [];
                windowsList.push(pickId);
                bindWindows(windowsList);
                th.lightwindow(entyties, windowsList, 0);
              } else if (th.isBind == 2) {
                th.isBind = 0;
                windowsList = [];
                windowsList.push(pickId);
                bindWindows(windowsList);
                th.lightwindow(entyties, windowsList, 0);
                //todo
                //取消绑定
              }
            }
          }
        },
        Cesium.ScreenSpaceEventType.LEFT_CLICK,
        Cesium.KeyboardEventModifier.CTRL
      );
    },
    getWindows(val) {
      let param = {
        zp_build_name: val.buildId,
        zp_household_danger_type: val.zpHouseholdDangerType,
      };
      this.$axios.getDangerWindows(param).then((res) => {
        if (res.code == 200) {
          console.log(res.data.length);
          if (res.data.length != 0 && res.data[0] != "") {
            this.lightwindow(
              this.entities,
              res.data,
              val.zpHouseholdDangerType
            );
          } else {
            this.resetWindowColor(this.entities);
            this.$message.warning("暂无户籍数据，请先绑定数据");
          }
        }
      });
      // this.isInit = 2;
    },
    closeWindows() {
      // console.log("val", val);
      this.resetWindowColor(this.entities);
    },
    resetWindowColor(entyties) {
      for (let i = 0; i < entyties._entities._array.length; i++) {
        if (entyties._entities._array[i].model) {
          entyties._entities._array[i].model.color = null;
        }
      }
    },
    lightwindow(entyties, windsId, type) {
      for (let i = 0; i < entyties._entities._array.length; i++) {
        if (entyties._entities._array[i].model) {
          entyties._entities._array[i].model.color = null;
        }
      }
      for (let i = 0; i < entyties._entities._array.length; i++) {
        for (let j = 0; j < windsId.length; j++) {
          if (entyties._entities._array[i]._id == windsId[j]) {
            if (entyties._entities._array[i].model) {
              entyties._entities._array[i].model.color =
                Cesium.Color.fromCssColorString(this.TypeColor[type]);
              // Cesium.Color.GREEN.withAlpha(0.5);
              break;
            }
          }
        }
      }
    },
    lightWindowNoClear(entyties, windsId, type) {
      for (let i = 0; i < entyties._entities._array.length; i++) {
        for (let j = 0; j < windsId.length; j++) {
          if (entyties._entities._array[i]._id == windsId[j]) {
            if (entyties._entities._array[i].model) {
              entyties._entities._array[i].model.color =
                Cesium.Color.fromCssColorString(this.TypeColor[type]);
              // Cesium.Color.GREEN.withAlpha(0.5);
              break;
            }
          }
        }
      }
    },
    // 点击变色
    changeModelColor() {},
    //移除所有handler
    removeAllHandler() {
      if (this.handlerBind) {
        this.handlerBind.removeInputAction(
          Cesium.ScreenSpaceEventType.LEFT_CLICK,
          Cesium.KeyboardEventModifier.CTRL
        );
        this.handlerBind = null;
      }
      if (this.handlerBuild) {
        this.handlerBuild.removeInputAction(
          Cesium.ScreenSpaceEventType.LEFT_CLICK
        ); //移除事件
        this.handlerBuild = null;
      }
      if (this.handler3D) {
        this.handler3D.removeInputAction(
          Cesium.ScreenSpaceEventType.LEFT_CLICK
        ); //移除事件
        this.handler3D = null;
      }
      if (this.handlerInfo) {
        this.handlerInfo.removeInputAction(
          Cesium.ScreenSpaceEventType.LEFT_CLICK
        ); //移除事件
        this.handlerInfo = null;
      }
    },
    closehomemodal() {
      this.isShowJoined = false;
    },
    // 获取连栋信息
    getJoinedInfo(label) {
      this.isShowJoined = false;
      this.buildId = label;
      this.loadClickHouse(label);
    },
    clickJoinedInfo(click) {
      // 屏幕坐标转世界坐标——关键点
      const ellipsoid = this.viewer.scene.globe.ellipsoid;
      const cartesian = this.viewer.camera.pickEllipsoid(
        click.position,
        ellipsoid
      );
      //将笛卡尔坐标转换为地理坐标
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      //将弧度转为度的十进制度表示
      const lon = Cesium.Math.toDegrees(cartographic.longitude);
      const lat = Cesium.Math.toDegrees(cartographic.latitude);

      const point2 = { longitude: lon, latitude: lat };
      this.click_point = Cesium.Cartesian3.fromDegrees(
        point2.longitude,
        point2.latitude
      );
      this.c = new Cesium.Cartesian2(click.position.x, click.position.y);
      this.target_position = click.position;
      this.cartesian_2 = cartesian;
      if (cartesian) {
        this.showJoinedInfo(click.position);
      }
    },
    showJoinedInfo(position) {
      if (position) {
        this.isShowJoined = true;
        this.joinedInfo.style.left = position.x + 30 + "px";
        this.joinedInfo.style.top = position.y - 50 + "px";
      }
    },
    initJoinedInfo(frameDiv, pickId) {
      this.options = [];
      this.selectJoined = null;
      this.joinedInfo = document.getElementById("joinedInfo");
      let joinedArray = this.joinedBuildData[pickId];
      for (let i = 0; i < joinedArray.length; i++) {
        this.options.push({
          value: i,
          label: joinedArray[i],
        });
      }

      frameDiv.appendChild(this.joinedInfo);
    },

    // 加载3dtiles
    add3dTiles(viewer) {
      var tileset = this.viewer.scene.primitives.add(
        new Cesium.Cesium3DTileset({
          url: "/tt/zp3dtiles/tileset.json",
          skipLevelOfDetail: true,
          baseScreenSpaceError: 1024,
          skipScreenSpaceErrorFactor: 16,
          skipLevels: 1,
          immediatelyLoadDesiredLevelOfDetail: false,
          loadSiblings: false,
          cullWithChildrenBounds: true,
        })
      );
      var blockTilest = this.viewer.scene.primitives.add(
        new Cesium.Cesium3DTileset({
          url: "/tt/ZpMergeTiles/tileset.json",
          skipLevelOfDetail: true,
          baseScreenSpaceError: 1024,
          skipScreenSpaceErrorFactor: 16,
          skipLevels: 1,
          immediatelyLoadDesiredLevelOfDetail: false,
          loadSiblings: false,
          cullWithChildrenBounds: true,
        })
      );
      tileset.readyPromise
        .then(function () {
          viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(
              103.260594,
              26.413065,
              800
            ),
            orientation: {
              heading: Cesium.Math.toRadians(0.0),
              pitch: Cesium.Math.toRadians(-25.0),
              roll: 0.0,
            },
          });
          tileset.tileVisible.addEventListener(function (tile) {
            var content = tile.content;
            var featuresLength = content.featuresLength;
            for (var i = 0; i < featuresLength; i += 2) {
              let feature = content.getFeature(i);
              let model = feature.content._model;

              if (model && model._sourcePrograms && model._rendererResources) {
                Object.keys(model._sourcePrograms).forEach((key) => {
                  let program = model._sourcePrograms[key];
                  let fragmentShader =
                    model._rendererResources.sourceShaders[
                      program.fragmentShader
                    ];
                  let v_position = "";
                  if (fragmentShader.indexOf(" v_positionEC;") != -1) {
                    v_position = "v_positionEC";
                  } else if (fragmentShader.indexOf(" v_pos;") != -1) {
                    v_position = "v_pos";
                  }
                  const color = `vec4(${feature.color.toString()})`;

                  model._rendererResources.sourceShaders[
                    program.fragmentShader
                  ] =
                    "varying vec3 " +
                    v_position +
                    ";\n" +
                    "void main(void){\n" +
                    "    vec4 position = czm_inverseModelView * vec4(" +
                    v_position +
                    ",1);\n" +
                    "    float glowRange = 360.0;\n" +
                    "    gl_FragColor = " +
                    color +
                    ";\n" +
                    // "    gl_FragColor = vec4(0.2,  0.5, 1.0, 1.0);\n" +
                    "    gl_FragColor *= vec4(vec3(position.z / 100.0), 1.0);\n" +
                    "    float time = fract(czm_frameNumber / 360.0);\n" +
                    "    time = abs(time - 0.5) * 2.0;\n" +
                    "    float diff = step(0.005, abs( clamp(position.z / glowRange, 0.0, 1.0) - time));\n" +
                    "    gl_FragColor.rgb += gl_FragColor.rgb * (2.0 - diff);\n" +
                    "}\n";
                });
                model._shouldRegenerateShaders = true;
              }
            }
          });
        })
        .otherwise(function (error) {
          console.error(error);
        });

      tileset.style = new Cesium.Cesium3DTileStyle({
        color: {
          conditions: [["true", "rgba(0, 127.5, 255 ,1)"]],
        },
      });
      blockTilest.style = new Cesium.Cesium3DTileStyle({
        color: {
          conditions: [
            ["${floor} >= 3", "rgba(3,31,53, 0.5)"],
            ["true", "rgba(3,31,53, 0.5)"],
          ],
        },
      });
    },
    returnSceneShow() {
      this.isBuilding = false;
      this.showSlid = false;
      this.userInfoShow = false;
      this.InfoEditShow = false;
      this.BindShow = false;
      this.isSubordinate = false;
      this.buildId = "null";
      this.returnScene();
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 2000);
    },
    returnScene() {
      this.removeAllHandler();
      this.isInit = 0;
      // if (this.addDiv) {
      //   this.SetVisible(false);
      // }
      this.show = false;
      this.viewer.entities.removeAll();
      this.models = [];
      this.addAllHouse();
      this.putLabels(
        this.labelName,
        this.labels,
        this.viewer,
        this.labelDatas,
        this.buildiColor,
        this.backImg,
        Cesium.HeightReference.NONE
      );
      this.putLabels(
        this.roadName,
        this.labels,
        this.viewer,
        this.roadLabel,
        this.roadColor,
        null,
        Cesium.HeightReference.CLAMP_TO_GROUND
      );
      // this.labels.show = true;
    },
    addGeoJson() {
      this.viewer.dataSources.add(
        Cesium.GeoJsonDataSource.load("/tt/TomCatZpJson/ZpRange.json", {
          stroke: Cesium.Color.fromCssColorString("#000d1e"),
          fill: Cesium.Color.fromCssColorString("#000d1e"),
          strokeWidth: 3,
        })
      );
    },
    addAllHouse() {
      for (let i = 0; i < this.buildingName.length; i++) {
        this.initHouse(
          "/tt/A5Merge/jianzhu_" +
            this.buildingData[this.buildingName[i]].name +
            ".gltf",
          Cesium.Cartesian3.fromDegrees(
            this.buildingData[this.buildingName[i]].lon,
            this.buildingData[this.buildingName[i]].lat,
            this.buildingData[this.buildingName[i]].height
          ),
          this.models,
          this.buildingName[i]
        );
      }
      // 最终加载
      this.addModel(this.models, this.entities);
    },
    startLoading() {
      this.loading = true;
    },
    endLoading() {
      this.loading = false;
      this.isInit = 1;
    },
    //
    loadClickHouse(buildingId) {
      let th = this;
      // console.log("isInit为" + th.isInit);
      // th.show = true;
      th.loading = true;
      // this.startLoading()
      setTimeout(function () {
        // console.log("关闭加载");
        th.endLoading();
      }, 2000);

      th.viewer.entities.removeAll();
      th.models = [];
      // 加载分离window  axios
      axios
        .get("/zz/redisWindow/windowUrls/" + buildingId)
        .then((res) => {
          // debugger;
          th.initHouse(
            "/tt/A5Split/jianzhu_" + buildingId + "_building.gltf",
            Cesium.Cartesian3.fromDegrees(
              this.includeJoinedData[buildingId].lon,
              this.includeJoinedData[buildingId].lat,
              this.includeJoinedData[buildingId].height
            ),
            th.models,
            buildingId
          );
          const urlArr = res.data[buildingId];
          for (let i = 0; i < urlArr.length; i++) {
            th.initClickWindow(
              "/zz/redisWindow/window/" + urlArr[i],
              Cesium.Cartesian3.fromDegrees(
                this.includeJoinedData[buildingId].lon,
                this.includeJoinedData[buildingId].lat,
                this.includeJoinedData[buildingId].height
              ),
              th.models,
              urlArr[i]
            );
          }

          th.addModel(this.models, this.entities);
          const clickLabel = {
            lon: th.labelDatas[buildingId].lon,
            lat: th.labelDatas[buildingId].lat,
            height: th.labelDatas[buildingId].height,
            name: buildingId,
          };
          th.putClickLabel(
            clickLabel,
            th.labels,
            th.viewer,
            th.buildiColor,
            th.backImg
          );
          th.putbuttonLabel(clickLabel, th.labels, th.viewer);
          // th.labels.show = true;

          // this.initTool(this.viewer.cesiumWidget.container);
          // this.clickEve(this.viewer);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    initScene() {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkMDJiNDIyZi02MWE1LTQwNWUtOGI3My1hNjU3YjRkZDBlMmYiLCJpZCI6NjcxNjUsImlhdCI6MTYzMjYyMjc5N30.8htzCJDY2O5nG46L6KV2w517GDIcDi9JOOHej9Kk7-M";

      this.viewer = new Cesium.Viewer("cesiumContainer", {
        geocoder: false, //位置查找工具
        homeButton: false, //复位按钮
        sceneModePicker: false, //模式切换
        baseLayerPicker: false, //图层选择
        navigationHelpButton: false, //帮助按钮
        animation: false, //速度控制
        timeline: false, //时间轴
        fullscreenButton: false, //全屏
        infoBox: false,
        selectionIndicator: false,

        // imageryProvider:new Cesium.WebMapServiceImageryProvider({
        //     url: "api/geoserver/zp/wms",
        //     layers: "zp:zp_range",
        //     parameters: {
        //       service: "WMS",
        //       format: "image/png",
        //       transparent: true,
        //       isPick: false,
        //     },
        //   })
      });
      // 添加geoserver图层
      // http://localhost:8080/geoserver/zp/wms?service=WMS&version=1.1.0&request=GetMap&layers=zp%3Azp_range&bbox=103.24705481529236%2C26.41862690448761%2C103.26671004295349%2C26.439194083213806&width=733&height=768&srs=EPSG%3A4326&styles=&format=application/openlayers
      // var provider = new Cesium.WebMapServiceImageryProvider({
      //   url: "api/geoserver/zp/wms",
      //   layers: "zp:zp_range",
      //   parameters: {
      //     service: "WMS",
      //     format: "image/png",
      //     transparent: true,
      //     isPick: false,
      //   },
      // });
      //
      // this.viewer.imageryLayers.addImageryProvider(provider);

      //加载mapbox风格底图
      // var layer = new Cesium.MapboxStyleImageryProvider({
      //   //https://api.mapbox.com/styles/v1/chenshushu/ckw0fqf7z0dc914qiwx7hmwp4.html?title=view&access_token=pk.eyJ1IjoiY2hlbnNodXNodSIsImEiOiJja3R1dWw0cDIwZWNhMndtbXB4bGRpZW5sIn0.H7uUDYpNWl1qBCRVWi1JKg&zoomwheel=true&fresh=true#20.27/26.4283346/103.2634973/147.2/62
      //   url: "https://api.mapbox.com/styles/v1",
      //   username: "chenshushu",
      //   styleId: "ckw0fqf7z0dc914qiwx7hmwp4",
      //   accessToken:
      //     "pk.eyJ1IjoiY2hlbnNodXNodSIsImEiOiJja3R1dWw0cDIwZWNhMndtbXB4bGRpZW5sIn0.H7uUDYpNWl1qBCRVWi1JKg",
      //   scaleFactor: true,
      //
      //   // styleId: "dark-v10",
      //   // accessToken:
      //   //   "pk.eyJ1IjoiY2hlbnNodXNodSIsImEiOiJja3R1dWw0cDIwZWNhMndtbXB4bGRpZW5sIn0.H7uUDYpNWl1qBCRVWi1JKg",
      // });
      // this.viewer.imageryLayers.addImageryProvider(layer);
      this.viewer.scene.globe.show = false;
      this.viewer._cesiumWidget._creditContainer.style.display = "none"; // 隐藏版权信息
      Cesium.Math.setRandomNumberSeed(1234);
      const utc = Cesium.JulianDate.fromDate(new Date("2019/10/04 7:00:00")); //UTC
      this.viewer.clock.currentTime = Cesium.JulianDate.addHours(
        utc,
        8,
        new Cesium.JulianDate()
      ); //北京时间=UTC+8=GMT+8
      // this.viewer.scene.globe.enableLighting = true;
      // this.viewer.shadows = true
      this.viewer.scene.light.intensity = 15;
      this.entities = this.viewer.entities;
      this.isInit = 0;
      this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );
      this.viewer.imageryLayers.get(0).show = false;
    },
    putLabels(
      datas,
      parent,
      viewer,
      labelDatas,
      fliiColor,
      backImg,
      heightReference
    ) {
      for (let i = 0; i < datas.length; i++) {
        let data = labelDatas[datas[i]];
        // let data = this.labelDatas[datas[i]];
        viewer.entities.add({
          name: "",
          //参数顺序：经度、纬度
          position: Cesium.Cartesian3.fromDegrees(
            data.lon,
            data.lat,
            data.height
          ), //标签的位置
          parent: parent,

          billboard: backImg,
          label: {
            text: data.name,
            font: "14pt MicroSoft YaHei",
            // backgroundColor : Cesium.Color.PINK,
            // showBackground:true,                //是否显示背景颜色
            style: Cesium.LabelStyle.FILL,
            fillColor: fliiColor,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
              0,
              3000
            ),
            // scaleByDistance : new Cesium.NearFarScalar(100, 2, 500, 0.0),
            verticalOrigin: Cesium.VerticalOrigin.TOP,
            pixelOffset: new Cesium.Cartesian2(0, -10), //此属性为设置偏移量
            heightReference: heightReference,
          },
          type: "text", //自定义属性
        });
      }
    },
    putbuttonLabel(data, parent, viewer) {
      viewer.entities.add({
        name: data.name + "_info",
        //参数顺序：经度、纬度
        position: Cesium.Cartesian3.fromDegrees(
          data.lon,
          data.lat,
          data.height
        ), //标签的位置
        parent: parent,
        billboard: {
          scale: 0.5,
          image: "button_s.png",
          pixelOffset: new Cesium.Cartesian2(0, -50),
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0,
            3000
          ),
        },
      });
    },
    putClickLabel(data, parent, viewer, fliiColor, backImg) {
      viewer.entities.add({
        name: "",
        //参数顺序：经度、纬度
        position: Cesium.Cartesian3.fromDegrees(
          data.lon,
          data.lat,
          data.height
        ), //标签的位置
        parent: parent,
        billboard: backImg,
        label: {
          text: data.name,
          font: "14pt MicroSoft YaHei",
          // showBackground:true,                //是否显示背景颜色
          style: Cesium.LabelStyle.FILL,
          fillColor: fliiColor,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0,
            3000
          ),
          // scaleByDistance : new Cesium.NearFarScalar(100, 2, 500, 0.0),
          outlineWidth: 3,
          verticalOrigin: Cesium.VerticalOrigin.TOP,
          pixelOffset: new Cesium.Cartesian2(0, -10), //此属性为设置偏移量
        },
        type: "text", //自定义属性
      });
    },
    // popJioned(viewer,entyties){
    //
    //
    // },
    rightShow(id) {
      this.showSlid = true;
      console.log("可以点击了，牛逼", id);
    },
    toBack() {
      this.showSlid = false;
    },
    leftClick() {
      this.show = true;
      this.userInfoShow = false;
      this.resetWindowColor(this.entities);
    },
    toClose() {
      this.show = false;
      this.resetWindowColor(this.entities);
    },
    toCloseLayer() {
      this.resetWindowColor(this.entities);
      this.userInfoShow = false;
    },
    toCloseInfoEdit() {
      this.InfoEditShow = false;
    },
    toDetail(val) {
      // console.log(val);
      this.detail = val;
      this.showSlid = true;
    },
    clickEve(viewer, entyties) {
      this.removeAllHandler();
      let th = this;
      th.handlerBuild = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

      th.handlerBuild.setInputAction(function (click) {
        if (th.isInit == 1) {
          const pick = viewer.scene.pick(click.position);
          if (
            pick &&
            pick.id &&
            pick.id._name != "" &&
            pick.id._name.indexOf("_info") != -1
          ) {
            th.InfoEditShow = true;
            // console.log("点击了楼栋", pick);
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      th.handlerInfo = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

      th.handlerInfo.setInputAction((click) => {
        th.userInfo = [];
        if (th.isInit == 1 && !th.show) {
          for (let i = 0; i < entyties._entities._array.length; i++) {
            if (entyties._entities._array[i].model) {
              entyties._entities._array[i].model.color = null;
            }
          }
          const pick = viewer.scene.pick(click.position);
          if (pick && pick.id && pick.id._id.indexOf("_w_") != -1) {
            th.windowId = pick.id._id;
            th.$axios
              .getHouseholdInfo({ windowId: pick.id._id })
              .then((res) => {
                if (res.code == 200) {
                  console.log("lengthlength", res.data.length);
                  if (res.data.length != 0) {
                    res.data.forEach((item) => {
                      if (item.zpHouseholdIdentity == "户主") {
                        th.householder.name = item.zpHouseholdName;
                        th.householder.address = item.zpHouseholdAdress;
                      }
                    });
                    th.userInfo = res.data;
                    th.userInfoShow = true;
                  } else {
                    th.userInfoShow = false;
                    th.$message.error("暂无人员信息");
                  }
                } else {
                  th.userInfoShow = false;
                  th.$message.error("暂无人员信息");
                }
              });

            th.isPickModel = true;
            for (let i = 0; i < entyties._entities._array.length; i++) {
              if (entyties._entities._array[i]._id == pick.id._id) {
                if (entyties._entities._array[i].model) {
                  entyties._entities._array[i].model.color =
                    Cesium.Color.BLUE.withAlpha(0.5);
                  break;
                }
              }
            }
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },

    initHouse(url, position, models, id) {
      var house = {
        id: id,
        name: "楼房11",
        position: position,
        url: url,
      };
      models.push(house);
    },
    //后台传入size 请求后台接口动态加载窗户
    initClickWindow(url, position, models, id) {
      //count 动态获取
      var window = {
        id: id,
        name: "窗户",
        position: position,
        url: url,
      };
      models.push(window);
    },

    //加载点击模型
    addModel(models, entities) {
      if (models && models.length > 0) {
        for (let i = 0; i < models.length; i++) {
          let heading = Cesium.Math.toRadians(65);
          var pitch = 0;
          var roll = 0;
          var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
          var orientation = Cesium.Transforms.headingPitchRollQuaternion(
            models[i].position,
            hpr
          );
          this.locatEntity = entities.add({
            name: models[i].name,
            id: models[i].id,
            position: models[i].position,
            orientation: orientation,
            model: {
              color: null,
              silhouetteColor: null,
              silhouetteAlpha: 0,
              silhouetteSize: 0,
              show: true,
              uri: models[i].url,
              scale: 1.0, // 缩放比例
              minimumPixelSize: 1, // 最小像素大小
              maximumScale: 1, // 模型的最大比例尺大小。 minimumPixelSize的上限
              incrementallyLoadTextures: true, // 加载模型后纹理是否可以继续流入
              runAnimations: true, // 是否应启动模型中指定的glTF动画
              clampAnimations: true, // 指定glTF动画是否应在没有关键帧的持续时间内保持最后一个姿势

              // 指定模型是否投射或接收来自光源的阴影 type:ShadowMode
              // DISABLED 对象不投射或接收阴影;ENABLED 对象投射并接收阴影;CAST_ONLY  对象仅投射阴影;RECEIVE_ONLY  对象仅接收阴影
              shadows: Cesium.ShadowMode.ENABLED,
              heightReference: Cesium.HeightReference.NONE,
            },
          });
        }
      }
    },

    //选中变色
    // eslint-disable-next-line no-unused-vars
    selectModel(viewer, entyties) {
      this.removeAllHandler();
      // console.log("isInit目前为" + this.isInit);
      //调用接口-气泡窗口
      this.handler3D = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      let th = this;
      this.handler3D.setInputAction(function (movement) {
        if (th.isInit == 0) {
          for (let i = 0; i < entyties._entities._array.length; i++) {
            if (entyties._entities._array[i].model) {
              entyties._entities._array[i].model.color = null;
            }
          }
          //点击变色
          var pick = viewer.scene.pick(movement.position);
          if (pick && pick.id && pick.id._position && pick.id._name != "") {
            const pickId = pick.id._id;
            th.buildId = pickId;
            // console.log("建筑", pickId);

            if (th.joinedBuild.indexOf(pickId) == -1) {
              if (th.isShowJoined == true) {
                th.isShowJoined = false;
              }
              th.loadClickHouse(pickId);
            } else if (th.joinedBuild.indexOf(pickId) != -1) {
              for (let i = 0; i < entyties._entities._array.length; i++) {
                if (entyties._entities._array[i]._id == pick.id._id) {
                  if (entyties._entities._array[i].model) {
                    entyties._entities._array[i].model.color =
                      Cesium.Color.BLUE.withAlpha(0.5);
                    break;
                  }
                }
              }
              th.options = [];
              let joinedArray = th.joinedBuildData[pickId];
              for (let i = 0; i < joinedArray.length; i++) {
                th.options.push({
                  value: i,
                  label: joinedArray[i],
                });
              }
              // th.initJoinedInfo(th.viewer.cesiumWidget.container, pickId);
              th.isShowJoined = true;
              th.buildId = "null";
              // th.clickJoinedInfo(movement);
            }
            //进入模型分离界面
          } else {
            th.isShowJoined = false;
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    // 边界检测功能关闭 耗性能
    edgeSupport(viewer, entyties) {
      // 鼠标滑过边界检测
      viewer.screenSpaceEventHandler.setInputAction(function onMouseMove(
        movement
      ) {
        for (let i = 0; i < entyties._entities._array.length; i++) {
          if (entyties._entities._array[i].model) {
            entyties._entities._array[i].model.silhouetteColor = null;
            entyties._entities._array[i].model.silhouetteAlpha = 0;
            entyties._entities._array[i].model.silhouetteSize = 0;
          }
        }
        var pickedFeature = viewer.scene.pick(movement.endPosition);
        if (!Cesium.defined(pickedFeature)) {
          return;
        }
        for (let i = 0; i < entyties._entities._array.length; i++) {
          if (
            entyties._entities._array[i]._id == pickedFeature.id._id &&
            entyties._entities._array[i].model
          ) {
            entyties._entities._array[i].model.silhouetteColor =
              Cesium.Color.YELLOW.withAlpha(0.5);
            entyties._entities._array[i].model.silhouetteAlpha = 1.0;
            entyties._entities._array[i].model.silhouetteSize = 2.0;
            break;
          }
        }
        // Highlight the feature if it's not already selected.
      },
      Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
  },
  unmounted() {
    window.rightDetail;
  },
};
</script>
<style lang="scss" scoped>
.bind {
  position: absolute;
  top: 300px;
  left: 600px;
}
.layer-cesium {
  width: 100%;
  height: 100vh;
  z-index: 1;
  #cesiumContainer {
    height: 100%;
  }
}
.indexposation {
  position: absolute;
  // top: 10px;
  left: -5px;
  width: 100%;
}
.flex {
  display: flex;
  justify-content: space-between;
}
.right {
  width: 493px;
  z-index: 3;
  position: absolute;
  right: 0;
}
.left {
  width: 460px;
}
.leftshow {
  position: absolute;
  top: 236px;
  width: 42px;
  height: 665px;
  background: url("../assets/images/leftOpen.png");
  background-repeat: no-repeat;
  z-index: 2;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
.userInfo {
  position: absolute;
  top: 244px;
  left: 482px;
  height: 665px;
  z-index: 2;
}
.leftback {
  position: absolute;
  top: 10px;
  padding: 3px 15px 5px 20px;
  background: rgba(255, 255, 255, 1);
  border-radius: 0 30px 30px 0;
  display: flex;
  align-items: center;
  z-index: 2;
  cursor: pointer;
}
.leftback div {
  font-size: 24px;
  color: #477eff;
  padding-right: 5px;
}
.icontext {
  color: #477eff;
  font-size: 36px;
  font-weight: bold;
}

.homebuild {
  position: absolute;
  width: 100%;
  z-index: 1;
  top: 393px;
  .infoEditbody {
    display: flex;
    justify-content: center;
  }
}
.homemodal {
  height: 295px;
  width: 488px;
  background: url("../assets/images/multipleBg.png");
  background-repeat: no-repeat;
  position: relative;
  z-index: 1;
  .homemodalcontent {
    .homemodalhead {
      text-align: left;
      font-size: 22px;
      color: #fff;
      padding: 32px 32px 0 32px;
      .homemodalheadDiv {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .homemodalheadText {
      }
    }
    .homemodalbody {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      color: #62edff;
      .homemodallable {
        width: 260px;
        height: 41px;
        background: rgba(5, 30, 50, 0.65);
        border: 1px solid #62edff;
        line-height: 41px;
        margin-bottom: 20px;
        cursor: pointer;
      }
    }

    .splitLine {
      // position: relative;
      // top: -28px;
    }
  }
}
.infoEdit {
  position: absolute;
  width: 100%;
  z-index: 1;
}
.infoEditbody {
  display: flex;
  justify-content: center;
}
.homeBg {
  position: absolute;
  left: 50px;
  bottom: 50px;
  z-index: 1;
  cursor: pointer;
}
.homeBtn {
  height: 74px;
  width: 180px;
  background: url("../assets/images/home.png");
  background-repeat: no-repeat;
  color: #fff;
  font-size: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.homrIcon i {
  font-size: 32px;
}
.homrIcon {
  margin-right: 20px;
}
.homeText {
  margin-top: -6px;
}
.bindmodalbody {
  font-size: 22px;
  color: #fff;
  text-align: center;
  padding: 10px 30px;
}
.bindred {
  color: #ffb549;
}
.bindtext {
  font-size: 20px;
  margin-top: 15px;
}
.bindbtn {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 0 50px;
  margin-top: 25px;
}
.delBingbtn {
  width: 84px;
  height: 35px;
  line-height: 35px;
  background: rgba(5, 30, 50, 0.65);
  border: 1px solid #ffb549;
  color: #ffb549;
  opacity: 1;
  border-radius: 5px;
  cursor: pointer;
}
.addBingbtn {
  width: 84px;
  height: 35px;
  line-height: 35px;
  background: rgba(5, 30, 50, 0.65);
  border: 1px solid #62edff;
  color: #62edff;
  opacity: 1;
  border-radius: 5px;
  cursor: pointer;
  margin: 5px 0;
}
</style>
